package edu.tamu.cs.studio;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GameView extends SurfaceView implements SurfaceHolder.Callback
{
	private static final String TAG = GameView.class.getSimpleName();
	private GameThread thread;
	private Piece piece;
	public GameView(Context context, AttributeSet attrs){super(context, attrs);}
	public GameView(Context context, AttributeSet attrs, int defStyle){super(context, attrs,defStyle);}

	
	public GameView(Context context) 
	{
		super(context);
		getHolder().addCallback(this);
		piece = new Piece(100,100);
		thread = new GameThread(getHolder(),this);
		setFocusable(false);
		
		// TODO Auto-generated constructor stub
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {
		// TODO Auto-generated method stub
		
	}

	public void surfaceCreated(SurfaceHolder holder) 
	{
		thread.setRunning(true);
		thread.start();
		// TODO Auto-generated method stub
	}

	public void surfaceDestroyed(SurfaceHolder holder)
	{
		Log.d(TAG, "Surface is being destroyedp");
		boolean retry = true;
		while(retry)
		{
			try
			{
				thread.join();
				retry = false;
			}
			catch(InterruptedException e){}
			
		}
		// TODO Auto-generated method stub
		Log.d(TAG, "Thread was shut down cleanly");
	}
	
	@Override	
	protected void onDraw(Canvas canvas)
	{
		Paint paint = new Paint();
		paint.setColor(Color.WHITE);
		String text = "x="+Integer.toString(this.getWidth());
		Bitmap scaledBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.gamescreen), 320, 480,true);
		canvas.drawBitmap(scaledBitmap,0,0,null);
		canvas.drawText(text, 25, 25, paint);
		piece.draw(canvas);
	}
	
	//public int[] board_corrdinates(int x, int y)
	//{
	//	int []l = new int[2];
	//}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{
		if (event.getAction() == MotionEvent.ACTION_DOWN) 
		{
			// delegating event handling to the piece
			if(event.getX() > 15 && event.getX() < 47 && event.getY() > 105 && event.getY() < 137)
			{
				piece.setX(31);
				piece.setY(121);
			}
			System.out.println(event.getX() + ",y= " + event.getY());
			// check if in the lower part of the screen we exit
			if (event.getY() > getHeight() - 50) 
			{
				thread.setRunning(false);
				((Activity)getContext()).finish();
			}
			
		} 
		if (event.getAction() == MotionEvent.ACTION_UP) 
		{
			// touch was released
			if (piece.isTouched())
			{
				piece.setTouched(false);
			}
		}
		return true;
	}
	
}

